import dayjs from "dayjs";
import editForm from "../form.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h } from "vue";
import type { FormItemProps } from "../utils/types";
import { cloneDeep, isAllEmpty, deviceDetection } from "@pureadmin/utils";
import { getAllOrganizations, createOrganization as create, updateOrganization as update, batchDeleteOrganization as batchDelete } from "@/swagger/api/organization";

export function useDept() {
  const form = reactive({
    name: "",
    enabled: null
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const { tagStyle } = usePublicHooks();

  const columns: TableColumnList = [
    {
      label: "组织名称",
      prop: "name",
      width: 180,
      align: "left"
    },
    {
      label: "排序",
      prop: "sort",
      minWidth: 70
    },
    {
      label: "状态",
      prop: "enabled",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={tagStyle.value(row.enabled)}>
          {row.enabled === true ? "启用" : "禁用"}
        </el-tag>
      )
    },
    {
      label: "创建时间",
      minWidth: 200,
      prop: "created",
      formatter: ({ created }) =>
        dayjs(created).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "备注",
      prop: "description",
      minWidth: 320
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const { data } = await getAllOrganizations(); // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    let newData = data as any[];
    if (!isAllEmpty(form.name)) {
      // 前端搜索组织名称
      newData = newData.filter(item => item.name.includes(form.name));
    }
    if (!isAllEmpty(form.enabled)) {
      // 前端搜索状态
      newData = newData.filter(item => item.enabled === form.enabled);
    }
    dataList.value = handleTree(newData); // 处理成树结构
    loading.value = false;
  }

  function formatHigherDeptOptions(treeList, parentDisabled = false) {
    if (!treeList || !treeList.length) return [];

    const newTreeList = [];
    for (let i = 0; i < treeList.length; i++) {
      const node = { ...treeList[i] }; // 避免修改原对象（可选）

      // 当前节点是否应被禁用：
      // 1. 自身未启用，或
      // 2. 父节点已被禁用
      const isSelfDisabled = !node.enabled;
      const isAncestorDisabled = parentDisabled;
      node.disabled = isSelfDisabled || isAncestorDisabled;

      // 递归处理子节点，并将当前节点的禁用状态作为“父级禁用”传下去
      if (node.children && node.children.length > 0) {
        node.children = formatHigherDeptOptions(node.children, node.disabled);
      }

      newTreeList.push(node);
    }
    return newTreeList;
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}组织`,
      props: {
        formInline: {
          higherDeptOptions: formatHigherDeptOptions(cloneDeep(dataList.value)),
          id: row?.id ?? null,
          parentId: row?.parentId ?? null,
          name: row?.name ?? null,
          code: row?.code ?? null,
          sort: row?.sort ?? 0,
          enabled: row?.enabled ?? true,
          description: row?.description ?? null
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了组织名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            // 表单规则校验通过
            if (title === "新增") {
              await create(curData)
              chores();
            } else {
              await update({ id: curData.id }, curData)
              chores();
            }
          }
        });
      }
    });
  }

  async function handleDelete(row) {
    await batchDelete({ organizationIds: [row.id] })
    message(`您删除了组织名称为${row.name}的这条数据`, { type: "success" });
    onSearch();
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    /** 新增、修改组织 */
    openDialog,
    /** 删除组织 */
    handleDelete,
    handleSelectionChange
  };
}
